:- module(term_list_conversion,
	[
	    atom_to_term_list/2,
	    term_list_to_atom/2,
	    my_term_to_atom/2
	]).

:- use_module(library(terms)).

% term_list_to_atom(+AList,-Atom)
% Converts a term containing a list of terms separated by blanks into 
% a list of those terms.
term_list_to_atom(AtomList,Atom):-
	term_list_to_atom_(AtomList,' ',Atom).

term_list_to_atom_([],_,'').
term_list_to_atom_([L0|Ls],Separator,Atom) :-
	my_term_to_atom(L0, L),
	add_preffix(Separator,Ls,Rs),
	atom_concat([L|Rs],Atom).

add_preffix(_Preffix, [], []).
add_preffix(Preffix, [L0|Ls], [R|Rs]) :-
	my_term_to_atom(L0, L),
	atom_concat(Preffix, L, R),
	add_preffix(Preffix,Ls,Rs).


% atom_to_term_list(+Atom,-AList)
% Converts a term containing a list of terms separated by blanks into 
% a list of those terms.
atom_to_term_list([],[]).
atom_to_term_list(Atom,AList):-
	atom(Atom),
	atom_codes(Atom,AtomCodes),
        skip_blanks_and_tabs(AtomCodes, AtomsRest),
	string_to_term_list(AtomsRest,AList),
	!.

skip_blanks_and_tabs([0' |Xs], Ys):- !, skip_blanks_and_tabs(Xs, Ys).
skip_blanks_and_tabs("\t"||Xs, Ys):- !, skip_blanks_and_tabs(Xs, Ys).
skip_blanks_and_tabs(Xs, Xs).

%string_to_term_list(+AtomS,-AList)
string_to_term_list([],[]).
string_to_term_list(AtomSList,[Nterm|AList]):-
	get_next_term(AtomSList,Atom0S,AtomSRest),
	atom_codes(Atom,Atom0S),
%jcf-- now in(...) and out(...) are just dictionary entries (and therefore they are atoms).
%	filter_in_out(Atom, Nterm),
	Atom=Nterm,
%jcf
	string_to_term_list(AtomSRest,AList).

get_next_term([],[],[]).
get_next_term([Sep1,Sep2|AtomSList],[],AtomSRest):-
	separator(Sep1),
	separator(Sep2),
	get_next_term([0' |AtomSList],[],AtomSRest).
get_next_term([Sep|AtomSList],[],AtomSList):-
	separator(Sep).
get_next_term([C|AtomSList],[C|AtomS],AtomSRest):-
	get_next_term(AtomSList,AtomS,AtomSRest).

separator(0' ).
separator(\t).

filter_in_out(Atom, Nterm) :-
	(
            do_filter(Atom, Name, ContentRPar) ->
            atom_concat(Content, ')', ContentRPar),
            functor(Nterm, Name, 1),
            arg(1, Nterm, Content)
        ;
            Atom = Nterm
        ).

do_filter(Atom, in, ContentRPar) :-  
        atom_concat('in(', ContentRPar, Atom).
do_filter(Atom, out, ContentRPar) :-
	atom_concat('out(', ContentRPar, Atom).
do_filter(Atom, stream, ContentRPar) :-
	atom_concat('stream(', ContentRPar, Atom).

my_term_to_atom(Term, Atom):-
        (
            functor(Term, Name, 1) ->
            arg(1, Term, Contents),
            atom_concat([Name, '(', Contents, ')'], Atom)
        ;
            Term = Atom
        ).

